/**
 * @file    mock 接口中间件
 * @author  zhangxueqiong@baidu.com
 */

const url = require('url');
const chalk = require('chalk');
const mockService = require('mockservice');
const { isProxyRemote, proxyServer } = require('./proxy');

module.exports = ({ debugFilePath } = {}) => {
  mockService.config({
    name: 'mockservice-test',
    dir: debugFilePath,
  });

  const proxyRequest = (request, response) => {
    const parsedUrl = url.parse(request.url, true);
    // 如果需要走代理
    if (isProxyRemote()) {
      // eslint-disable-next-line no-console
      console.log(chalk.bgGreen(`[REMOTE DEBUG] PATH: ${parsedUrl.pathname}`));
      proxyServer.web(request, response);
      return;
    }
    const serve = mockService.serve;
    request.query = parsedUrl.query || {};
    const data = [];
    request.on('data', (trunk) => {
      data.push(trunk && trunk.toString());
    });
    request.on('end', (trunk) => {
      if (trunk) {
        data.push(trunk.toString());
      }
      request.body = data.join('');
      serve(request, response);
    });
  };

  return (req, res, next) => {
    if (req.method === 'POST' || req.method === 'GET') {
      proxyRequest(req, res);
    } else {
      next();
    }
  };
};
